<?php
namespace app\service;

use think\facade\Cache;
/**
 * @author yanxusheng <[<ausheng@foxmail.com>]>
 * @datetime 2023/6/16 15:20
 * @content
 */
class Random
{
    public string $cache_tag = "RANDOM-OPTIONS-LIST";
    public string $cache_key = "RANDOM-%s-CODE-USERS-%s";
    public string $cache_val = "";


    /**
     * @param string $option
     * @param string $users
     * @param int $min
     * @param int $max
     * @return int
     */
    public function createRandom(string $option, string $users, int $min = 100000, int $max = 999999): int
    {
        $this->cache_key = sprintf($this->cache_key, $option, $users);
        $this->cache_val = rand($min, $max);

        // 存储 redis （ 其实这个也应该放到 service 层 ）
        Cache::tag($this->cache_tag)->set($this->cache_key, $this->cache_val, 60 *10);
        return true;
    }


    /**
     * @param string $option
     * @param string $users
     * @param string $value
     * @return bool
     */
    public function verifyRandom(string $option, string $users, string $value): bool
    {
        $this->cache_key = sprintf($this->cache_key, $option, $users);
        $this->cache_val = Cache::get($this->cache_key);

        if (!$this->cache_val || $this->cache_val != $value) {
            return false;
        } else {
            return true;
        }
    }
}